package com.bort.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bort.system.info.LoginResult;
import com.bort.system.mapper.MenuMapper;
import com.bort.system.mapper.RoleUserMapper;
import com.bort.system.mapper.UserMapper;
import com.bort.system.mapper.UserVipLogMapper;
import com.bort.system.model.Menu;
import com.bort.system.model.RoleUser;
import com.bort.system.model.User;
import com.bort.system.model.UserVipLog;
import com.bort.system.model.vo.Admin;
import com.bort.system.model.vo.VipUser;
import com.bort.system.service.UserService;
import com.bort.system.utils.Result;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl  extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${uploadRootPath:D:/workspace/bort/src/main/resources/static/}")
    private String root;

    @Resource
    UserMapper userMapper;

    @Resource
    RoleUserMapper roleUserMapper;

    @Resource
    MenuMapper menuMapper;

    @Resource
    UserVipLogMapper vipLogMapper;


    @Override
    public LoginResult login(String username, String password) {
        LoginResult result = new LoginResult();
        result.setState("fail");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        List<User> users = userMapper.selectList(queryWrapper);
        if(users.size() ==0 ){
            result.setMsg("用户不存在");
        }else if(users.size() > 1){
            result.setMsg("用户存在异常");
        }else{
            String passwordEnc = new Md5Hash(password).toString();
            if(passwordEnc.equals(users.get(0).getPassword())){
                result.setState("success");
                result.setData(users.get(0));
            }else{
                result.setMsg("密码错误");
            }
        }
        return result;
    }

    @Override
    public List<Menu> selectPromisedMenus(Integer userId) {
        return userMapper.selectPromisedMenus(userId);
    }

    @Override
    public void selectByPage(Page<Admin> pager, Map<String,Object> map) {
      List<Admin> list = userMapper.getUserList(pager,map);
      pager.setRecords(list);
    }


    /**
     * 添加管理员
     **/
    @Override
    public void insetAdmin(Admin admin) {
        admin.setType((byte) 1);
        admin.setCreateTime(new Date());
        userMapper.insertSelective(admin);
        saveRoles(admin.getId(), admin.getRole());
    }

    // 分配管理员角色
    private void saveRoles(Integer id, List<Integer> role) {
        for (int roleId : role) {
            RoleUser roleUser = new RoleUser();
            roleUser.setRoleId(roleId);
            roleUser.setUserId(id);
            roleUserMapper.insertSelective(roleUser);
        }
    }

    @Override
    public User findByUserName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        List<User> users = userMapper.selectList(wrapper);
        if(users != null && users.size() > 0){
            return users.get(0);
        }
        return null;
    }

    @Override
    public List<Menu> getUserAuthorizedMenus(Integer id) {
        return menuMapper.selectUserAuthorizedMenus(id);
    }

    @Override
    public Result upload(MultipartFile file) {
        Result<Object> result = new Result<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
        String path = "upload/"+dateFormat.format(new Date());
        File dir =  new File(root+path);
        if(!dir.isDirectory()){
            dir.mkdirs();
        }
        String orgName = file.getOriginalFilename();
        String suffix = orgName.substring(orgName.lastIndexOf("."));
        String fileName = RandomStringUtils.randomAlphabetic(4)+System.currentTimeMillis()/1000 + suffix;
        try {
            File target = new File(root+path+"/"+fileName);
            file.transferTo(target);
            result.setData(path+"/"+fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result.setCode(0);
            result.setMsg(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            result.setCode(0);
            result.setMsg(e.getMessage());
        }

        return result;
    }

    @Override
    public void selectVipUsers(Page<VipUser> pager, Map<String, Object> map) {
        List<VipUser> list = userMapper.getVipUserList(pager,map);
        pager.setRecords(list);
    }

    @Override
    public Result updatePassword(Map<String, Object> map) {
        if(map != null && map.get("id") != null){
            int userId = Integer.parseInt(map.get("id").toString());
            User user = getById(userId);
            String passwordEnc = new Md5Hash(map.get("password")).toString();
            user.setPassword(passwordEnc);
            updateById(user);
            return Result.success();
        }
        return Result.error("参数有误");
    }

    /**
     * 更新管理员
     **/
    @Override
    public void updateAdmin(Admin admin) {
        userMapper.updateByPrimaryKeySelective(admin);
        roleUserMapper.deleteByUserId(admin.getId());
        saveRoles(admin.getId(), admin.getRole());
    }

    @Override
    public void updateUser(User user) {
        updateById(user);
    }

    @Override
    public void addUser(User user) {
        Date now = new Date();
        Subject subject = SecurityUtils.getSubject();
        User admin = (User) subject.getPrincipal();
        user.setCreateTime(now);
        user.setCreateUserId(admin.getId());
        if(user.getExtra() == null){
            user.setExtra(new BigDecimal(0));
        }
        user.setBalance(user.getCharge().add(user.getExtra()));
        save(user);
        UserVipLog vip = new UserVipLog();
        vip.setUserId(user.getId());
        vip.setCharge(user.getCharge());
        vip.setExtra(user.getExtra());
        vip.setBalance(user.getBalance());
        vip.setCreateTime(now);
        vip.setCrateUserId(admin.getCreateUserId());
        vipLogMapper.insert(vip);
    }

    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteByPrimaryKey(id);
        vipLogMapper.deleteByUserId(id);
    }

}
